/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.coupon.handler;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.gson.JsonObject;
import com.ykht.proj.admin.api.entity.SysSocialDetails;
import com.ykht.proj.common.core.constant.CacheConstants;
import com.ykht.proj.common.core.constant.SecurityConstants;
import com.ykht.proj.common.core.constant.enums.LoginTypeEnum;
import com.ykht.proj.coupon.entity.CnPerson;
import com.ykht.proj.coupon.mapper.CnPersonMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author proj
 * @date 2019年11月02日
 * <p>
 * 微信小程序
 */
@Slf4j
@Component("BAIDU_C")
@RequiredArgsConstructor
public class BaiduAppLoginHandler extends AbstractLoginHandler {

	private final CnPersonMapper cnPersonMapper;
	private final RedisTemplate redisTemplate;


	/**
	 * 小程序登录传入code
	 * <p>
	 * 通过code 调用qq 获取唯一标识
	 * @param code
	 * @return
	 */
	@Override
	public String identify(String code) {
		SysSocialDetails condition = new SysSocialDetails();
		condition.setType(LoginTypeEnum.MINI_APP.getType());
		//SysSocialDetails socialDetails = sysSocialDetailsMapper.selectOne(new QueryWrapper<>(condition));

		//暂时这么处理，后续改成调用服务获取
		String url = SecurityConstants.BAIDU_APP_AUTHORIZATION_CODE_URL+"?sk=LTHxOqhUIWpqcmvFfOxRqTepYiiiQT6O&client_id=AXyshyIcnAGohCVzGAtpvDFNuzC3GqmF&code="+code;
		String result = HttpUtil.get(url);
		log.debug("微信小程序响应报文:{}", result);

		Object openId = JSONUtil.parseObj(result).get("openid");
		Object sessionKey = JSONUtil.parseObj(result).get("session_key");
//		openId="o7xw-5NxoLCQgYCb3eLZkyKSzBU4";
		if(null != openId && null != sessionKey){
			redisTemplate.opsForValue().set(CacheConstants.USER_SEEESINKEY_BY_OPENID+openId.toString(), sessionKey.toString());
		}
		log.info("->openid:{}",openId);
		return String.valueOf(openId);
	}

	/**
	 * openId 获取用户信息
	 * @param openId
	 * @return
	 */
	@Override
	public Object info(String openId) {

		CnPerson person = cnPersonMapper.selectOne(Wrappers.lambdaQuery(CnPerson.class).eq(CnPerson::getOpenId,openId));
		if (null != person) return person;
		log.info("->首次登陆，创建用户openid：{}",openId);
		CnPerson temp = new CnPerson();
		temp.setOpenId(openId);
		temp.setStatus(0);
		temp.setCreateTime(LocalDateTime.now());
		temp.setCreateUser(temp.getId());
		temp.setLoginType(1);//百度
		temp.insert();
		return temp;
	}

}
